package com.xiaobaibai.units.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaobaibai.bo.SubscribeMessageBo;
import com.xiaobaibai.bo.pay.WxPayCreateOrder;
import com.xiaobaibai.common.PayCommon;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.UUID;

public class HttpClientUnit {

    @SuppressWarnings("all")
    public static JSONObject get(String url){

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpGet httpGet = new HttpGet(url);

        // 响应模型
        CloseableHttpResponse response = null;

        try {

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(getRequestConfig());

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            return JSONObject.parseObject(EntityUtils.toString(responseEntity));

        } catch (ParseException | IOException e) {
            e.printStackTrace();
            return new JSONObject();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static RequestConfig getRequestConfig(){
        // 配置信息
        return RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();
    }

    @SuppressWarnings("all")
    public static JSONObject messagePost(String url, SubscribeMessageBo subscribeMessageBo){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(url);

        // 响应模型
        CloseableHttpResponse response = null;

        try {

            String body = JSON.toJSONString(subscribeMessageBo);
            StringEntity entity = new StringEntity(body, "UTF-8");

            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);

            // 将上面的配置信息 运用到这个Get请求里
            httpPost.setConfig(getRequestConfig());

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            return JSONObject.parseObject(EntityUtils.toString(responseEntity));

        } catch (ParseException | IOException e) {
            e.printStackTrace();
            return new JSONObject();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //支付请求
    public static JSONObject wxPayPost(String url, WxPayCreateOrder wxPayCreateOrder){
        return post(url,wxPayCreateOrder);
    }

    private static JSONObject post(String url,Object object){

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(url);

        // 响应模型
        CloseableHttpResponse response = null;

        try {

            String body = JSON.toJSONString(object);
            StringEntity entity = new StringEntity(body, "UTF-8");

            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);

            /**
             * 获取签名
             */
            String uuid= UUID.randomUUID().toString().substring(0,32);
            long timestamp=System.currentTimeMillis()/1000;
            String key = KeyPairFactory.sign("POST", "/v3/pay/transactions/jsapi", timestamp, uuid, body, KeyPairFactory.createPKCS12());
            String authorization = "WECHATPAY2-SHA256-RSA2048 "+KeyPairFactory.getPayHeard(PayCommon.mchid, uuid, timestamp, PayCommon.serialNumber, key);
//            String authorization= null;
//            try {
//                authorization = "WECHATPAY2-SHA256-RSA2048 "+WxPayUnit签名生成.getToken("POST",url,timestamp,uuid,body);
//            } catch (SignatureException | NoSuchAlgorithmException | InvalidKeyException e) {
//                e.printStackTrace();
//            }
            //放入签名
            httpPost.setHeader("Authorization",authorization);
            httpPost.setHeader("Content-Type","application/json");
            httpPost.setHeader("Accept", "application/json");
//            httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36");

            // 将上面的配置信息 运用到这个Get请求里
            httpPost.setConfig(getRequestConfig());

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            return JSONObject.parseObject(EntityUtils.toString(responseEntity));

        } catch (ParseException | IOException e) {
            e.printStackTrace();
            return new JSONObject();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
